package com.rankeiot.easy.vue.handler;

import com.rankeiot.easy.vue.EasyVueConfiguration;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;



public class VueDevHandler implements HandlerInterceptor {
    private ResourceLoader resourceLoader;
    public VueDevHandler(ResourceLoader resourceLoader){
        this.resourceLoader=resourceLoader;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(HttpMethod.GET.matches(request.getMethod())){
            String path=request.getRequestURI();
            Resource resource= resourceLoader.getResource("classpath:/static"+path);
            if(resource.exists()){
                if(EasyVueConfiguration.devModel){
                    response.setHeader("Cache-Control","no-store");
                }
                return true;
            }

            String newPath = path.substring(0, path.length() - 3) + "js";
            resource= resourceLoader.getResource("classpath:/static"+newPath);
            if(resource.exists()){
                request.getRequestDispatcher(newPath)
                    .forward(request,response);
            }
        }
        return true;
    }
}
